import { makeAutoObservable, autorun, runInAction } from "mobx";
import { loginApi } from "../../api/modules/user";

// 1. 设置数据类
class UserStore {
    // 声明state数据
    user = JSON.parse(localStorage.getItem("user")) || {
        token: "",
        username: "",
        headpic: "",
        permissions: []
    };
    //   3. 声明数据为响应式
    constructor() {
        makeAutoObservable(this);
    }
    //   设置修改数据的方法

    async login(data) {
        let res = await loginApi(data);
        runInAction(() => {
            this.user.token = res.token;
            this.user.username = res.user.username;
            this.user.headpic = res.user.headpic;
            this.user.permissions = res.user.permissions;
        })
        return res;
    }
    async logout() {
        this.user.token = '';
        this.user.username = '';
        this.user.headpic = '';
        this.user.permissions = [];
    }

}

const userStroe = new UserStore();
autorun(() => {
    localStorage.setItem("user", JSON.stringify(userStroe.user));
});

export default userStroe;